//
//  GifImageView.m
//  boot
//
//  Created by Demi on 14/03/2017.
//  Copyright © 2017 Azazie. All rights reserved.
//

#import "GifImageView.h"

#import "UIImage+Gif.h"
#import "BaseLog.h"
#import "TXFire.h"
#import <Masonry/Masonry.h>
#import <ReactiveObjC/ReactiveObjC.h>

@interface GifImageView ()

@property (nonatomic, strong) RACDisposable *disposable;

@property (nonatomic, assign) NSTimeInterval duration;
@property (nonatomic, strong) NSArray *images;

@property (nonatomic, strong) NSMutableArray *remainingAnimatedImages;

@property (nonatomic, assign) BOOL isLoaded;

@end

@implementation GifImageView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self commontInit];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        [self commontInit];
    }
    return self;
}

- (void)commontInit
{
    @weakify(self);
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationDidReceiveMemoryWarningNotification object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(id x){
        @strongify(self);
        [self suspend];
        [self displayLastFrame];
        self.remainingAnimatedImages = nil;
        self.images = nil;
        self.isLoaded = NO;
    }];
}

- (void)setGifPath:(NSString *)gifPath
{
    if (!string_equivalent(_gifPath, gifPath))
    {
        _gifPath = [gifPath copy];
        [self loadImagesForGif];
    }
}

- (BOOL)loadImagesForGif
{
    self.isLoaded = YES;
    NSTimeInterval duration = 0;
    NSArray *images = [UIImage imagesWithContentsOfFile:_gifPath duration:&duration];
    if (images.count > 0)
    {
        _images = [images copy];
        _duration = duration;
        return YES;
    }
    else
    {
        _images = nil;
        _duration = 0;
        DLog(@"%@", @"The file you provided is not exist or not a gif.");
        return NO;
    }
}

- (void)displayFirstFrame
{
    self.image = _images.firstObject;
}

- (void)displayLastFrame
{
    self.images = _images.lastObject;
}

- (void)start
{
    self.remainingAnimatedImages = nil;
    [self resume];
}

- (void)resume
{
    if (!_gifPath)
    {
        return;
    }
    
    [self suspend];
    
    if (!self.isLoaded)
    {
        [self loadImagesForGif];
    }
    
    if (self.images.count <= 1)
    {
        return;
    }
    
    if (!self.remainingAnimatedImages)
    {
        self.remainingAnimatedImages = [self.images mutableCopy];
    }
    
    NSTimeInterval interval = _duration / (double)self.images.count;
    @weakify(self);
    RACDisposable *disposable = [[[RACSignal interval:interval onScheduler:[RACScheduler mainThreadScheduler]] startWith:[NSDate date]] subscribeNext:^(id x){
        @strongify(self);
        if (!self)
        {
            return;
        }
        if (self.remainingAnimatedImages.count > 0)
        {
            self.image = self.remainingAnimatedImages.firstObject;
            [self.remainingAnimatedImages removeObjectAtIndex:0];
        }
        else
        {
            self.remainingAnimatedImages = nil;
            [self suspend];
        }
    }];
    self.disposable = disposable.asScopedDisposable;
}

- (void)suspend
{
    [self.disposable dispose];
    self.disposable = nil;
}

@end
